package com.jse.util;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;

public class Xmls extends com.jse.lang.Xmls {
	
	/**
	 * 转换对象为xml
	 * @param obj
	 * @return
	 */
	public static String toXml(Object obj) {
		if(obj instanceof List) {
			return toXml((List<?>)obj);
		}else if(obj instanceof Map) {
			return toXml((Map<?,?>)obj);
		}else if(obj instanceof File) {
			try {
				File f=(File) obj;
				String xml=new String(Files.readAllBytes(Paths.get(f.getPath())));
				return xml;
			} catch (IOException e) {
				return "";
			}
		}else {
			return obj.toString();
		}
	}
	/**
	 * 转换list对象 xml
	 * @param obj
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static String toXml(List<?> obj) {
		StringBuffer xml=new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
		String root="xml";
		xml.append("<"+root+">\n");
		for (int i = 0; i < obj.size(); i++) {
			Object item=obj.get(i);
			if(item instanceof Map) {
				Map<String, Object> map=(Map<String, Object>) item;
				map.put("desc", "");
				map.put("root", "table");
				String str=toXml(map);
				xml.append(str).append("\n");
			}else {
				xml.append("<item"+i+">").append(obj.get(i)).append("</item"+i+">\n");
			}
		}

		xml.append("</"+root+">");
		return xml.toString();
	}
	/**
	 * 转换map对象 xml
	 * @param obj
	 * @return
	 */
	public static String toXml(Map<?, ?> obj) {
		String desc="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
		if(obj.containsKey("desc")) {
			desc=obj.get("desc").toString();
			obj.remove("desc");
		}
		StringBuffer xml=new StringBuffer(desc);
		String root="xml";
		if(obj.containsKey("root")) {
			root=obj.get("root").toString();
			obj.remove("root");
		}
		xml.append("<"+root+">\n");
		obj.forEach((k,v)->{
			xml.append("<"+k+">").append(v).append("</"+k+">\n");
		});
		xml.append("</"+root+">");
		return xml.toString();
	}

	public static void main(String[] args) {
		System.err.println(toXml(new File("D:\\work\\jes\\1.xml")));
	}
	
}
